package diploma.kisel.modelas.gui;

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.EventQueue;
import java.util.List;
import java.util.Vector;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.Border;
import javax.swing.border.EmptyBorder;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import javax.swing.BorderFactory;
import javax.swing.JOptionPane;
import javax.swing.ListSelectionModel;
import javax.swing.SpringLayout;
import javax.swing.JScrollPane;
import javax.swing.JTable;

import diploma.kisel.modelas.domain.Computer;
import diploma.kisel.modelas.domain.ComputerType;
import diploma.kisel.modelas.gui.common.Const;
import diploma.kisel.modelas.gui.common.CurrentVar;
import diploma.kisel.modelas.service.ComputerServiceImpl;
import diploma.kisel.modelas.service.UserServiceImpl;
import diploma.kisel.modelas.service.api.ComputerService;
import diploma.kisel.modelas.service.api.UserService;

import static diploma.kisel.modelas.service.StaticHelper.*;
import static diploma.kisel.modelas.validation.Validation.*;

import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.Component;

/**
 * This window is designed for showing all computers from database and
 * allows users to add new computer, edit or delete them.
 * 
 * @author Nikolay Kisel
 *
 */
public class ComputerCatalogWindow extends JFrame {

	private static ComputerCatalogWindow frame;

	private int row;
	private JPanel contentPane;
	private static JTable table;
	private static DefaultTableModel model;
	private JScrollPane scrollPane;
	private static Vector<Vector<Object>> tableData;

	private JLabel label;
	private JTextField textFieldMinPrice;
	private JTextField textFieldMaxPrice;
	private JButton buttonAdd;
	private JButton buttonClose;

	// Defines frame this window has come from
	private boolean isFromServerWindow = false;
	private boolean isFromWorkpalceWindow = false;

	private ServerWindow currServerWindow;
	private WorkplaceWindow currWorkplaceWindow;

	private ComputerService computerService = new ComputerServiceImpl();
	private UserService userService = new UserServiceImpl();
	private JLabel label_2;
	private JTextField textField;

	/**
	 * Create the frame.
	 */
	public ComputerCatalogWindow() {
		setTitle("Каталог компьютеров");
		// setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 508, 553);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		SpringLayout sl_contentPane = new SpringLayout();
		contentPane.setLayout(sl_contentPane);

		scrollPane = new JScrollPane();
		sl_contentPane.putConstraint(SpringLayout.NORTH, scrollPane, 104,
				SpringLayout.NORTH, contentPane);
		sl_contentPane.putConstraint(SpringLayout.WEST, scrollPane, 0,
				SpringLayout.WEST, contentPane);
		sl_contentPane.putConstraint(SpringLayout.EAST, scrollPane, 0,
				SpringLayout.EAST, contentPane);
		contentPane.add(scrollPane);

		
		table = new JTable(modelSetting(model, computerService.findAll()));
//		if (isFromServerWindow)
//			table = new JTable(modelSetting(model, computerService.findByType(ComputerType.Server)));
		TableColumn col = table.getColumnModel().getColumn(0);
		col.setMinWidth(0);
		col.setMaxWidth(0);

		table.setAutoCreateRowSorter(true);
		scrollPane.setViewportView(table);

		table.addMouseListener(new MouseAdapter() {
			public void mouseClicked(MouseEvent e) {
				if (e.getClickCount() == 2) {
					Computer comp = new Computer();
					comp.setId((Integer) table.getValueAt(row, 0));
					comp.setNumber((String) table.getValueAt(row, 1));
					comp.setBrand((String) table.getValueAt(row, 2));
					comp.setCost((Integer) table.getValueAt(row, 3));
					comp.setFeatures((String) table.getValueAt(row, 4));
					comp.setType((ComputerType) table.getValueAt(row, 5));
					if (!isFromServerWindow && !isFromWorkpalceWindow) {
						ComputerWindow computerWindow = new ComputerWindow();
						ComputerWindow.setFrame(computerWindow);
						computerWindow.setComputer(comp);
						computerWindow.init();
						computerWindow.setVisible(true);
					} else {
						if (isFromServerWindow) {
							currServerWindow.setNewModelForPC(comp);

						} else {
							currWorkplaceWindow.setNewModelForPC(comp);

						}
						JOptionPane.showMessageDialog(frame, "ПЭВМ добавлена.");

					}
				}
			}
		});

		ListSelectionModel listSelMod = table.getSelectionModel();
		listSelMod.addListSelectionListener(new ListSelectionListener() {

			@Override
			public void valueChanged(ListSelectionEvent e) {
				row = table.getSelectedRow();
				// System.out.println(row);
			}
		});

		buttonAdd = new JButton("Добавить");
		sl_contentPane.putConstraint(SpringLayout.SOUTH, scrollPane, -14,
				SpringLayout.NORTH, buttonAdd);
		buttonAdd.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				Computer comp = new Computer();
				ComputerWindow computerWindow = new ComputerWindow();
				ComputerWindow.setFrame(computerWindow);
				computerWindow.setComputer(comp);
				computerWindow.setVisible(true);
				computerWindow.getBtnDelete().setVisible(false);

			}
		});
		contentPane.add(buttonAdd);

		buttonClose = new JButton("Закрыть");
		sl_contentPane.putConstraint(SpringLayout.EAST, buttonClose, 0,
				SpringLayout.EAST, contentPane);
		buttonClose.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				frame.setVisible(false);
			}
		});
		sl_contentPane.putConstraint(SpringLayout.SOUTH, buttonClose, 0,
				SpringLayout.SOUTH, contentPane);
		sl_contentPane.putConstraint(SpringLayout.NORTH, buttonAdd, 0,
				SpringLayout.NORTH, buttonClose);
		sl_contentPane.putConstraint(SpringLayout.EAST, buttonAdd, -8,
				SpringLayout.WEST, buttonClose);
		contentPane.add(buttonClose);

		JPanel panelFiltr = new JPanel();
		sl_contentPane.putConstraint(SpringLayout.NORTH, panelFiltr, 0, SpringLayout.NORTH, contentPane);
		sl_contentPane.putConstraint(SpringLayout.WEST, panelFiltr, 0,
				SpringLayout.WEST, scrollPane);
		sl_contentPane.putConstraint(SpringLayout.SOUTH, panelFiltr, -6, SpringLayout.NORTH, scrollPane);
		sl_contentPane.putConstraint(SpringLayout.EAST, panelFiltr, 0,
				SpringLayout.EAST, scrollPane);
		contentPane.add(panelFiltr);
		SpringLayout sl_panelFiltr = new SpringLayout();
		panelFiltr.setLayout(sl_panelFiltr);

		label = new JLabel("Макс. цена:");
		sl_contentPane.putConstraint(SpringLayout.NORTH, label, 0,
				SpringLayout.NORTH, panelFiltr);
		sl_contentPane.putConstraint(SpringLayout.WEST, label, 0,
				SpringLayout.WEST, panelFiltr);
		panelFiltr.add(label);

		textFieldMinPrice = new JTextField();
		sl_panelFiltr.putConstraint(SpringLayout.NORTH, label, 3,
				SpringLayout.NORTH, textFieldMinPrice);
		sl_panelFiltr.putConstraint(SpringLayout.WEST, label, 20,
				SpringLayout.EAST, textFieldMinPrice);
		sl_panelFiltr.putConstraint(SpringLayout.NORTH, textFieldMinPrice, 10,
				SpringLayout.NORTH, panelFiltr);
		sl_contentPane.putConstraint(SpringLayout.NORTH, textFieldMinPrice, 10,
				SpringLayout.NORTH, panelFiltr);
		sl_contentPane.putConstraint(SpringLayout.WEST, textFieldMinPrice, 21,
				SpringLayout.EAST, label);
		panelFiltr.add(textFieldMinPrice);
		textFieldMinPrice.setColumns(10);

		JLabel label_1 = new JLabel("Мин. цена:");
		sl_panelFiltr.putConstraint(SpringLayout.WEST, textFieldMinPrice, 13, SpringLayout.EAST, label_1);
		sl_panelFiltr.putConstraint(SpringLayout.NORTH, label_1, 13,
				SpringLayout.NORTH, panelFiltr);
		sl_panelFiltr.putConstraint(SpringLayout.WEST, label_1, 10,
				SpringLayout.WEST, panelFiltr);
		sl_contentPane.putConstraint(SpringLayout.WEST, label_1, 0,
				SpringLayout.WEST, panelFiltr);
		sl_contentPane.putConstraint(SpringLayout.NORTH, label_1, 3,
				SpringLayout.NORTH, textFieldMinPrice);
		panelFiltr.add(label_1);

		textFieldMaxPrice = new JTextField();
		sl_panelFiltr.putConstraint(SpringLayout.NORTH, textFieldMaxPrice, -3,
				SpringLayout.NORTH, label);
		sl_panelFiltr.putConstraint(SpringLayout.WEST, textFieldMaxPrice, 15,
				SpringLayout.EAST, label);
		sl_contentPane.putConstraint(SpringLayout.WEST, textFieldMaxPrice, 24,
				SpringLayout.EAST, label);
		sl_contentPane.putConstraint(SpringLayout.SOUTH, textFieldMaxPrice,
				-10, SpringLayout.SOUTH, panelFiltr);
		panelFiltr.add(textFieldMaxPrice);
		textFieldMaxPrice.setColumns(10);

		Border raisedbevel = BorderFactory.createRaisedBevelBorder();
		Border loweredbevel = BorderFactory.createLoweredBevelBorder();
		Border compound = BorderFactory.createCompoundBorder(raisedbevel,
				loweredbevel);
		panelFiltr.setBorder(compound);
		
				JButton button = new JButton("Фильтровать");
				sl_panelFiltr.putConstraint(SpringLayout.WEST, button, 0, SpringLayout.WEST, textFieldMaxPrice);
				sl_panelFiltr.putConstraint(SpringLayout.SOUTH, button, -10, SpringLayout.SOUTH, panelFiltr);
				sl_contentPane.putConstraint(SpringLayout.NORTH, button, 244, SpringLayout.SOUTH, textFieldMinPrice);
				sl_contentPane.putConstraint(SpringLayout.WEST, button, 350, SpringLayout.WEST, panelFiltr);
				sl_contentPane.putConstraint(SpringLayout.SOUTH, button, -10, SpringLayout.SOUTH, panelFiltr);
				sl_contentPane.putConstraint(SpringLayout.EAST, button, -23, SpringLayout.EAST, panelFiltr);
				panelFiltr.add(button);
				
				label_2 = new JLabel("Марка:");
				sl_panelFiltr.putConstraint(SpringLayout.NORTH, label_2, 18, SpringLayout.SOUTH, label_1);
				sl_panelFiltr.putConstraint(SpringLayout.WEST, label_2, 0, SpringLayout.WEST, label_1);
				panelFiltr.add(label_2);
				
				textField = new JTextField();
				sl_panelFiltr.putConstraint(SpringLayout.NORTH, textField, -3, SpringLayout.NORTH, label_2);
				sl_panelFiltr.putConstraint(SpringLayout.WEST, textField, 0, SpringLayout.WEST, textFieldMinPrice);
				panelFiltr.add(textField);
				textField.setColumns(10);
				button.addActionListener(new ActionListener() {
					public void actionPerformed(ActionEvent arg0) {
						if (isNumber(textFieldMinPrice.getText())) {
							int minPrice = Integer.valueOf(textFieldMinPrice.getText());
							if (isNumber(textFieldMaxPrice.getText())) {
								int maxPrice = Integer.valueOf(textFieldMaxPrice
										.getText());
								String brand = textField.getText();			
								ComputerType type = ComputerType.User;
								if (isFromServerWindow)
									type = ComputerType.Server;
//								System.out.println(minPrice + " " + maxPrice);
								List<Computer> computersFindByPriceAndType = 
										computerService.findByPriceAndBrand(minPrice, maxPrice, type);
								List<Computer> computersFindByBrand = computersFindByPriceAndType;
								if (!brand.equals(""))
										computersFindByBrand=computerService.findByBrand(computersFindByPriceAndType, brand);
								table.setModel(modelSetting(model,computersFindByBrand));
								TableColumn col = table.getColumnModel().getColumn(0);
								col.setMinWidth(0);
								col.setMaxWidth(0);

								// scrollPane.setViewportView(table);
							} else
								JOptionPane.showMessageDialog(frame,
										"Введено неверное число.");
						} else
							JOptionPane.showMessageDialog(frame,
									"Введено неверное число.");

					}
				});

		if (userService.checkRole(CurrentVar.getCurrentUser(),
				Const.studentRole)) {
			System.out.println("OK");
			buttonAdd.setVisible(false);
		}
	}

	public static DefaultTableModel modelSetting(DefaultTableModel model,
			List<Computer> computers) {

		tableData = new Vector<Vector<Object>>();
		// List<Computer> computers=computerService.findAll();
		for (Computer computer : computers) {
			Vector<Object> currRow = new Vector<Object>();
			currRow.add(computer.getId());
			currRow.add(nullToEmptyString(computer.getNumber()));
			currRow.add(nullToEmptyString(computer.getBrand()));
			currRow.add(computer.getCost());
			currRow.add(nullToEmptyString(computer.getFeatures()));
			currRow.add(computer.getType());
			tableData.add(currRow);
		}

		Vector<String> columnName = new Vector<String>();
		columnName.add("Ид");
		columnName.add("Номер");
		columnName.add("Марка");
		columnName.add("Стоимость");
		columnName.add("Характеристики");
		columnName.add("Тип");

		model = new DefaultTableModel(tableData, columnName) {

			private static final long serialVersionUID = 1L;		

			public boolean isCellEditable(int row, int col) {
				return false;
			}

		};

		return model;
	}

	public static void setNewModel(List<Computer> computers) {
		table.setModel(modelSetting(model, computers));
		TableColumn col = table.getColumnModel().getColumn(0);
		col.setMinWidth(0);
		col.setMaxWidth(0);
	}

	public static ComputerCatalogWindow getFrame() {
		return frame;
	}

	public static void setFrame(ComputerCatalogWindow frame) {
		ComputerCatalogWindow.frame = frame;
	}

	public boolean isFromServerWindow() {
		return isFromServerWindow;
	}

	public void setFromServerWindow(boolean isFromServerWindow) {
		this.isFromServerWindow = isFromServerWindow;
	}

	public ServerWindow getCurrServerWindow() {
		return currServerWindow;
	}

	public void setCurrServerWindow(ServerWindow currServerWindow) {
		this.currServerWindow = currServerWindow;
	}

	public boolean isFromWorkpalceWindow() {
		return isFromWorkpalceWindow;
	}

	public void setFromWorkpalceWindow(boolean isFromWorkpalceWindow) {
		this.isFromWorkpalceWindow = isFromWorkpalceWindow;
	}

	public WorkplaceWindow getCurrWorkplaceWindow() {
		return currWorkplaceWindow;
	}

	public void setCurrWorkplaceWindow(WorkplaceWindow currWorkplaceWindow) {
		this.currWorkplaceWindow = currWorkplaceWindow;
	}
}
